import xlrd
import numpy as np
import matplotlib.pyplot as plt
from npPCR import *
#一个xlsx文件导入解析器
class STDsheetReader:
    def __init__(self, filename,sheetName,headerIndex=0,fileType="xlsx"):
        self.sheet=None
        if fileType=="xlsx":
            self.sheet=xlrd.open_workbook(filename).sheet_by_name(sheetName)
        elif fileType=="xls":
            self.sheet=xlrd.open_workbook_xls(filename).sheet_by_name(sheetName)
        else:
            print("type error")
            exit(0)
        self.headerLoc=headerIndex
        self.headlist=[str(i) for i in self.sheet.row_values(self.headerLoc)]
        self.clen=len(self.headlist)
        self.tn=self.sheet.nrows
    def getTotualRowNum(self):
        return self.sheet.nrows
    def get_oneRow(self,rowindex):
        if rowindex >= self.tn:
            return None
        else:
            return self.sheet.row_values(rowindex)
    def get_lineRow(self):
        start = self.headerLoc+1
        end = self.tn
        for i in range(start,end):
            yield self.sheet.row_values(i)
    def get_lineDict(self):
        start = self.headerLoc+1
        end = self.tn
        for i in range(start,end):
            linedict={}
            for j in range(self.clen):
                linedict[self.headlist[j]]=self.sheet.row_values(i)[j]
            yield linedict
def Get_Income(flight):
    return flight['飞机座位数']*flight['客座率(%)']*flight['全价票价格']*flight['平均折扣率']
def Get_Cost(flight):
    return flight['机组人员工资(元)']+flight['航油费(元)']+flight['起降及非航空性业务费(元)']+flight['餐食(元)']+flight['机供品(元)']+flight['保险费-旅客责任险(元)']+flight['航材消耗(元)']+flight['不正常航班费用(元)']+flight['航材维修费(元)']+flight['发动机维修费(元)']
def Peek_One_flight(flight):
    line = []
    Peek_list =['飞机座位数','客座率(%)','全价票价格','平均折扣率','机组人员工资(元)','航油费(元)','起降及非航空性业务费(元)','餐食(元)','机供品(元)','保险费-旅客责任险(元)','航材消耗(元)','不正常航班费用(元)','航材维修费(元)','发动机维修费(元)']
    for key in Peek_list:
        line.append(flight[key])
    return line



if __name__=='__main__':
    sheet = STDsheetReader('./data/附件1XX航空公司某年某月某日航线成本(收入)明细表.xls','Sheet2',1,"xls")
    profit_array=[]
    peek_array=[]
    i =0 
    for one_flight in sheet.get_lineDict():
        income = Get_Income(one_flight)
        cost = Get_Cost(one_flight)
        profit = income-cost
        peek_array.append(Peek_One_flight(one_flight))
        profit_array.append(profit)
        i+=1
    j=0
    
    Y = np.array(profit_array)
    X = np.array(peek_array)
    print('输入维度：',X.shape)
    print('输出维度：',Y.shape)
    pcr = myPCR(X,Y)
    # compares = pcr.confirmPCs()
    # print(compares)
    # k= int(input("K value:"))
    # pcr.fit(k)

    pcr.Auto_confirmfit(threshold=0.99999)
    x_alx=[]
    y1_alx=[]
    y2_alx=[]
    print(pcr.A)
    print(pcr.A[1:])
    paramEnd = np.matmul(pcr.P,pcr.A[1:].T)
    print("---------------------")
    for c in paramEnd:
        print(c)
    print(paramEnd)
    while j<i:
        x_alx.append(j)
        y1_alx.append(pcr.predict(X[j]))
        y2_alx.append(profit_array[j])
        j+=1
    plt.xlabel("flight index")
    plt.ylabel("profit")
    # x_stick = np.linspace(1, 5, 52)
    # plt.xticks(x_stick)
    plt.plot(x_alx,y2_alx,color='red',label="source")
    plt.plot(x_alx,y1_alx,color='blue',label="our predictions")
    plt.legend() 
    plt.show()